<?php

namespace app\admin\controller;

use app\common\controller\AdminBase;
use think\Db;
use think\Request;

class Money extends AdminBase
{
    protected $classes_model;

    protected $money_model;

    public function __construct()
    {
        parent::__construct();
        $this->classes_model = new \app\common\model\Classes();
        $this->money_model = new \app\common\model\Money();
    }

    public function index($class_id = 0, $name = '', $phone = '', $id_card = '',$status = -1, $page = 1){
        $map = [];

        if ($status > -1) {
            $map['m.status']   = $status;
        }

        if ($class_id > 0) {
            $map['s.class_id'] = $class_id;
        }

        if (!empty($name)) {
            $map['s.name']    = ['like', "%{$name}%"];
        }

        if (!empty($phone)) {
            $map['s.phone']   = ['like', "%{$phone}%"];
        }

        if (!empty($id_card)) {
            $map['s.id_card'] = ['like', "%{$id_card}%"];
        }

        $money_list = Db::table('os_money')
            ->alias('m')
            ->join('os_student s', 's.id = m.student_id', 'LEFT')
            ->join('os_class c', 'c.id = s.class_id', 'LEFT')
            ->where($map)
            ->order('m.update_time DESC, m.id DESC')
            ->field('m.id, m.prac_amount, m.status, m.mode, m.user_id, m.update_time,
                          s.name, s.phone, s.id_card, c.class_name')  // 指定查询字段
            ->paginate(10, false, ['page' => $page]);

        $class_list = $this->classes_model->all();

        return $this->fetch('index',[
            'class_list' => $class_list,
            'money_list' => $money_list,
            'class_id'   => $class_id,
            'name'       => $name,
            'phone'      => $phone,
            'id_card'    => $id_card,
            'status'     => $status,
        ]);
    }

    /**
     * 交费
     */
    public function pay(Request $request){
        $id = $request->param('id');
        $data = $request->param();
        $data['status'] = 1;

        $validate_result = $this->validate($data,'Money');
        if ($validate_result !== true) {
            $this->error($validate_result);
        }

        $result = $this->money_model->allowField(true)->isUpdate(true)->save($data,$id);
        if ($result) {
            $this->success('保存成功');
        } else {
            $this->error('保存失败');
        }
    }
}